import { ChatContext } from '@/app/chat-context';
import { apiInterceptors, getAppInfo, getChatHistory, getDialogueList } from '@/client/api';
import useChat from '@/hooks/use-chat';
import ChatContentContainer from '@/new-components/chat/ChatContentContainer';
import ChatDefault from '@/new-components/chat/content/ChatDefault';
// import ChatDefault from '@/new-components/chat/content/ChatDefaultWelcome';
import ChatInputPanel from '@/new-components/chat/input/ChatInputPanel';
import ChatSider from '@/new-components/chat/sider/ChatSider';
import { IApp } from '@/types/app';
import { ChartData, ChatHistoryResponse, IChatDialogueSchema } from '@/types/chat';
import { getInitMessage } from '@/utils';
import { useAsyncEffect, useRequest } from 'ahooks';
import { Flex, Layout, Spin } from 'antd';
import dynamic from 'next/dynamic';
import { useSearchParams } from 'next/navigation';
import React, { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { STORAGE_USERINFO_KEY } from '@/utils/constants/index';
import ChatExcelAnalyze from '@/components/chat-excel/chat_excel'

const DbEditor = dynamic(() => import('@/components/chat/db-editor'), {
  ssr: false,
});
const ChatContainer = dynamic(() => import('@/components/chat/chat-container'), { ssr: false });

const { Content } = Layout;

interface ChatContentProps {
  history: ChatHistoryResponse; // 会话记录列表
  replyLoading: boolean; // 对话回复loading
  scrollRef: React.RefObject<HTMLDivElement>; // 会话内容可滚动dom
  canAbort: boolean; // 是否能中断回复
  chartsData: ChartData[];
  agent: string;
  currentDialogue: IChatDialogueSchema; // 当前选择的会话
  appInfo: IApp;
  temperatureValue: any;
  maxNewTokensValue: any;
  resourceValue: any;
  modelValue: string;
  setModelValue: React.Dispatch<React.SetStateAction<string>>;
  setTemperatureValue: React.Dispatch<React.SetStateAction<any>>;
  setMaxNewTokensValue: React.Dispatch<React.SetStateAction<any>>;
  setResourceValue: React.Dispatch<React.SetStateAction<any>>;
  setAppInfo: React.Dispatch<React.SetStateAction<IApp>>;
  setAgent: React.Dispatch<React.SetStateAction<string>>;
  setCanAbort: React.Dispatch<React.SetStateAction<boolean>>;
  setReplyLoading: React.Dispatch<React.SetStateAction<boolean>>;
  handleChat: (content: string, data?: Record<string, any>) => Promise<void>; // 处理会话请求逻辑函数
  refreshDialogList: () => void;
  refreshHistory: () => void;
  refreshAppInfo: () => void;
  setHistory: React.Dispatch<React.SetStateAction<ChatHistoryResponse>>;

  showAnalysis: boolean;  // 展示 iframe更多分析页面
  setShowAnalysis: React.Dispatch<React.SetStateAction<boolean>>;
}
export const ChatContentContext = createContext<ChatContentProps>({
  history: [],
  replyLoading: false,
  scrollRef: { current: null },
  canAbort: false,
  chartsData: [],
  agent: '',
  currentDialogue: {} as any,
  appInfo: {} as any,
  temperatureValue: 0.5,
  maxNewTokensValue: 1024,
  resourceValue: {},
  modelValue: '',
  setModelValue: () => {},
  setResourceValue: () => {},
  setTemperatureValue: () => {},
  setMaxNewTokensValue: () => {},
  setAppInfo: () => {},
  setAgent: () => {},
  setCanAbort: () => {},
  setReplyLoading: () => {},
  refreshDialogList: () => {},
  refreshHistory: () => {},
  refreshAppInfo: () => {},
  setHistory: () => {},
  handleChat: () => Promise.resolve(),

  showAnalysis: false,
  setShowAnalysis: () => {},
});

const Chat: React.FC = () => {
  const [userInfo, setUserInfo] = useState(null);
  localStorage.setItem('CHAT_FROM', '');
  const [showAnalysis, setShowAnalysis] = useState(false);
  const { model, currentDialogInfo } = useContext(ChatContext);
  const { isContract, setIsContract, setIsMenuExpand } = useContext(ChatContext);
  const { chat, ctrl } = useChat({
    app_code: currentDialogInfo.app_code || '',
  });

  const searchParams = useSearchParams();
  const chatId = searchParams?.get('id') ?? '';
  const scene = searchParams?.get('scene') ?? '';
  const knowledgeId = searchParams?.get('knowledge_id') ?? '';
  const dbName = searchParams?.get('db_name') ?? '';

  const scrollRef = useRef<HTMLDivElement>(null);
  const order = useRef<number>(1);

  const [history, setHistory] = useState<ChatHistoryResponse>([]);
  const [chartsData] = useState<Array<ChartData>>();
  const [replyLoading, setReplyLoading] = useState<boolean>(false);
  const [canAbort, setCanAbort] = useState<boolean>(false);
  const [agent, setAgent] = useState<string>('');
  const [appInfo, setAppInfo] = useState<IApp>({} as IApp);
  const [temperatureValue, setTemperatureValue] = useState();
  const [maxNewTokensValue, setMaxNewTokensValue] = useState();
  const [resourceValue, setResourceValue] = useState<any>();
  const [modelValue, setModelValue] = useState<string>('');

  useEffect(() => {
    // 在组件挂载后（客户端）获取 localStorage 数据
    const storedUserInfo = localStorage.getItem(STORAGE_USERINFO_KEY);
    if (storedUserInfo) {
      setUserInfo(JSON.parse(storedUserInfo));
    }
  }, []);

  useEffect(() => {
    setTemperatureValue(appInfo?.param_need?.filter(item => item.type === 'temperature')[0]?.value || 0.6);
    setMaxNewTokensValue(appInfo?.param_need?.filter(item => item.type === 'max_new_tokens')[0]?.value || 4000);
    setModelValue(appInfo?.param_need?.filter(item => item.type === 'model')[0]?.value || model);
    setResourceValue(
      knowledgeId || dbName || appInfo?.param_need?.filter(item => item.type === 'resource')[0]?.bind_value,
    );
  }, [appInfo, dbName, knowledgeId, model]);

  useEffect(() => {
    // 仅初始化执行，防止dashboard页面无法切换状态
    setIsMenuExpand(scene !== 'chat_dashboard');
    // 路由变了要取消Editor模式，再进来是默认的Preview模式
    if (chatId && scene) {
      setIsContract(false);
    }
  }, [chatId, scene]);

  // 是否是默认小助手
  const isChatDefault = useMemo(() => {
    return !chatId && !scene;
  }, [chatId, scene]);

  // 获取会话列表
  const {
    data: dialogueList = [],
    refresh: refreshDialogList,
    loading: listLoading,
  } = useRequest(async () => {
    return await apiInterceptors(getDialogueList({ne_chat_mode:"chat_with_db_metric_model_qa,chat_excel_analyze"}));
  });

  // 获取应用详情
  const { run: queryAppInfo, refresh: refreshAppInfo } = useRequest(
    async () =>
      await apiInterceptors(
        getAppInfo({
          ...currentDialogInfo,
        }),
      ),
    {
      manual: true,
      onSuccess: data => {
        const [, res] = data;
        setAppInfo(res || ({} as IApp));
      },
    },
  );

  // 列表当前活跃对话
  const currentDialogue = useMemo(() => {
    const [, list] = dialogueList;
    return list?.find(item => item.conv_uid === chatId) || ({} as IChatDialogueSchema);
  }, [chatId, dialogueList]);

  useEffect(() => {
    const initMessage = getInitMessage();
    // if (currentDialogInfo.chat_scene === scene && !isChatDefault && !(initMessage && initMessage.message)) {
    if (currentDialogInfo.chat_scene === scene && !isChatDefault ) {
      queryAppInfo();
    }
  }, [chatId, currentDialogInfo, isChatDefault, queryAppInfo, scene]);

  // 获取会话历史记录
  const {
    run: getHistory,
    loading: historyLoading,
    refresh: refreshHistory,
  } = useRequest(async () => await apiInterceptors(getChatHistory(chatId)), {
    manual: true,
    onSuccess: data => {
      const [, res] = data;
      // res.push(
      //    {
      //       "role": "view",
      //       context: "```agent-messages\n[{\"sender\": \"IdxScientist\", \"receiver\": \"Human\", \"model\": \"deepseek-r1-distill-qwen\", \"markdown\": \"```vis-forecast-report\\n{\\\"type\\\": \\\"VisForecastReport\\\", \\\"metricModelId\\\": 74, \\\"metricColumnName\\\": \\\"sum_t_432_total_amount\\\", \\\"predictStep\\\": \\\"5\\\", \\\"question\\\": \\\"用户Gina Reynolds在2023年的订单总金额是多少？,用户Gina Reynolds在2024年的订单总金额是多少？,用户Gina Reynolds在2025年的订单总金额预测值是多少？\\\", \\\"data\\\": \\\"[{\\\\\\\"date\\\\\\\": \\\\\\\"2023\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 580154.48, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2024\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 533116.51, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": null, \\\\\\\"arima\\\\\\\": 486078.54000000027}, {\\\\\\\"date\\\\\\\": \\\\\\\"2026\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": null, \\\\\\\"arima\\\\\\\": 439040.5700000004}, {\\\\\\\"date\\\\\\\": \\\\\\\"2027\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": null, \\\\\\\"arima\\\\\\\": 392002.60000000056}, {\\\\\\\"date\\\\\\\": \\\\\\\"2028\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": null, \\\\\\\"arima\\\\\\\": 344964.6300000007}, {\\\\\\\"date\\\\\\\": \\\\\\\"2029\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": null, \\\\\\\"arima\\\\\\\": 297926.66000000085}]\\\"}\\n```\", \"resource\": null}]\n```",
      //       // "context": "```agent-messages\n[{\"sender\": \"IdxScientist\", \"receiver\": \"Human\", \"model\": \"Qwen/Qwen2.5-32B-Instruct\", \"markdown\": \"```vis-forecast-report\\n{\\\"type\\\": \\\"VisForecastReport\\\", \\\"metricModelId\\\": \\\"42\\\", \\\"metricColumnName\\\": \\\"260:price\\\", \\\"predictStep\\\": \\\"12\\\", \\\"question\\\": \\\"2025年每个月的总销售额是多少,2025年各商品的销售趋势如何,2025年哪些商品的销售额增长最快\\\", \\\"data\\\": \\\"[{\\\\\\\"date\\\\\\\": \\\\\\\"2025-01-01\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 241341.8901386261, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-01-02\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 265169.3700361252, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-01-03\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 273635.1002149582, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-01-04\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 256096.55028533936, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-01-05\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 258913.9401140213, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-01-06\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 248856.40000247955, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-01-07\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 269715.12966537476, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-01-08\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 273463.29980659485, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-01-09\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 271415.7200164795, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-01-10\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 273924.3500652313, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-01-11\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 257978.6697654724, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-01-12\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 270265.5800418854, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-01-13\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 242487.6397151947, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-01-14\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 269037.9000377655, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-01-15\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 278337.6097288132, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-01-16\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 266426.1498632431, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-01-17\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 276083.7899198532, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-01-18\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 266672.3890981674, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-01-19\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 234650.53039169312, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-01-20\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 273765.53993320465, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-01-21\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 257560.86003017426, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-01-22\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 267466.869764328, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-01-23\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 237484.1905002594, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-01-24\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 259019.38026809692, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-01-25\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 264008.48951148987, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-01-26\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 243361.42038154602, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-01-27\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 273014.58946990967, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-01-28\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 279036.8895664215, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-01-29\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 263512.5802965164, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-01-30\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 277218.5400457382, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-01-31\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 281082.5302619934, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-02-01\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 241814.56991672516, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-02-02\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 283608.4901418686, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-02-03\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 256749.78986167908, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-02-04\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 280983.82968330383, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-02-05\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 265111.8706073761, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-02-06\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 238049.109705925, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-02-07\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 265429.74932670593, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-02-08\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 275279.8800125122, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-02-09\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 244767.59992408752, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-02-10\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 246404.46982955933, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-02-11\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 241815.32991027832, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-02-12\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 261624.96969509125, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-02-13\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 266256.2499485016, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-02-14\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 286924.5600233078, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-02-15\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 265191.03992652893, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-02-16\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 265924.1399240494, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-02-17\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 249006.97012233734, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-02-18\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 268246.62966918945, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-02-19\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 216295.559841156, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-02-20\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 266849.5498714447, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-02-21\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 253164.50932502747, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-02-22\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 289614.1100139618, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-02-23\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 269515.69932842255, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-02-24\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 272510.80990314484, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-02-25\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 274751.1797571182, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-02-26\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 263892.569858551, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-02-27\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 272354.27013111115, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-02-28\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 266951.81973457336, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-03-01\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 269584.340385437, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-03-02\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 255906.85994148254, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-03-03\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 258829.56004619598, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-03-04\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 252682.69989967346, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-03-05\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 248518.2994966507, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-03-06\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 229507.36018562317, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2025-03-07\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": 206157.7399406433, \\\\\\\"arima\\\\\\\": null}, {\\\\\\\"date\\\\\\\": \\\\\\\"2026-01-01\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": null, \\\\\\\"arima\\\\\\\": 256689.16}, {\\\\\\\"date\\\\\\\": \\\\\\\"2026-01-02\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": null, \\\\\\\"arima\\\\\\\": 256284.63}, {\\\\\\\"date\\\\\\\": \\\\\\\"2026-01-03\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": null, \\\\\\\"arima\\\\\\\": 255880.1}, {\\\\\\\"date\\\\\\\": \\\\\\\"2026-01-04\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": null, \\\\\\\"arima\\\\\\\": 255475.57}, {\\\\\\\"date\\\\\\\": \\\\\\\"2026-01-05\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": null, \\\\\\\"arima\\\\\\\": 255071.04}, {\\\\\\\"date\\\\\\\": \\\\\\\"2026-01-06\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": null, \\\\\\\"arima\\\\\\\": 254666.51}, {\\\\\\\"date\\\\\\\": \\\\\\\"2026-01-07\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": null, \\\\\\\"arima\\\\\\\": 254261.98}, {\\\\\\\"date\\\\\\\": \\\\\\\"2026-01-08\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": null, \\\\\\\"arima\\\\\\\": 253857.45}, {\\\\\\\"date\\\\\\\": \\\\\\\"2026-01-09\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": null, \\\\\\\"arima\\\\\\\": 253452.91}, {\\\\\\\"date\\\\\\\": \\\\\\\"2026-01-10\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": null, \\\\\\\"arima\\\\\\\": 253048.38}, {\\\\\\\"date\\\\\\\": \\\\\\\"2026-01-11\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": null, \\\\\\\"arima\\\\\\\": 252643.85}, {\\\\\\\"date\\\\\\\": \\\\\\\"2026-01-12\\\\\\\", \\\\\\\"test\\\\\\\": null, \\\\\\\"train\\\\\\\": null, \\\\\\\"arima\\\\\\\": 252239.32}]\\\"}\\n```\", \"resource\": null}]\n```",
      //       "order": 1,
      //       "time_stamp": null,
      //       "model_name": "deepseek-r1-distill-qwen",
      //       "feedback": {}
      //   }
      // )
      const viewList = res?.filter(item => item.role === 'view');
      if (viewList && viewList.length > 0) {
        order.current = viewList[viewList.length - 1].order + 1;
      }
      setHistory(res || []);
    },
  });

  // 会话提问
  const handleChat = useCallback(
    (content: string, data?: Record<string, any>) => {
      return new Promise<void>(resolve => {
        const initMessage = getInitMessage();
        const ctrl = new AbortController();
        setReplyLoading(true);
        if (history && history.length > 0) {
          const viewList = history?.filter(item => item.role === 'view');
          const humanList = history?.filter(item => item.role === 'human');
          order.current = (viewList[viewList.length - 1]?.order || humanList[humanList.length - 1]?.order) + 1;
        }
        const tempHistory: ChatHistoryResponse = [
          ...(initMessage && initMessage.id === chatId ? [] : history),
          {
            role: 'human',
            context: content,
            model_name: data?.model_name || modelValue,
            order: order.current,
            time_stamp: 0,
          },
          {
            role: 'view',
            context: '',
            model_name: data?.model_name || modelValue,
            order: order.current,
            time_stamp: 0,
            thinking: true,
          },
        ];
        const index = tempHistory.length - 1;
        setHistory([...tempHistory]);
        chat({
          data: {
            chat_mode: scene,
            model_name: modelValue,
            user_input: content,
            ...data,
          },
          ctrl,
          chatId,
          onMessage: message => {
            setCanAbort(true);
            if (data?.incremental) {
              tempHistory[index].context += message;
              tempHistory[index].thinking = false;
            } else {
              tempHistory[index].context = message;
              tempHistory[index].thinking = false;
            }
            setHistory([...tempHistory]);
          },
          onDone: () => {
            setReplyLoading(false);
            setCanAbort(false);
            resolve();
          },
          onClose: () => {
            setReplyLoading(false);
            setCanAbort(false);
            resolve();
          },
          onError: message => {
            setReplyLoading(false);
            setCanAbort(false);
            tempHistory[index].context = message;
            tempHistory[index].thinking = false;
            setHistory([...tempHistory]);
            resolve();
          },
        });
      });
    },
    [chatId, history, modelValue, chat, scene],
  );

  useAsyncEffect(async () => {
    // 如果是默认小助手，不获取历史记录
    if (isChatDefault) {
      return;
    }
    const initMessage = getInitMessage();
    if (initMessage && initMessage.id === chatId) {
      return;
    }
    await getHistory();
  }, [chatId, scene, getHistory]);

  useEffect(() => {
    if (isChatDefault) {
      order.current = 1;
      setHistory([]);
    }
  }, [isChatDefault]);

  useEffect(() => {
    // 监听来自 iframe 的消息
    const handleMessage = (event: MessageEvent) => {
      console.log('接收 更多分析子页面 传递过来的数据 :', event.data);
      // if (event.data.type === 'ANALYSIS_QUERY') {
      //   const chatParams = {
      //     ...event.data.payload,
      //     chat_mode: scene,
      //     model_name: modelValue || model,
      //     user_input: event.data.payload.content || '',
      //     app_code: currentDialogInfo?.app_code,
      //     conv_uid: chatId
      //   }

      //   handleChat(event.data.payload.content|| '',chatParams)
      // }
      //关闭 右侧 更多分析页面
      if (event.data.type === 'CLOSE_ANALYSIS') {
        setShowAnalysis(false);
      }
    };

    window.addEventListener('message', handleMessage);
    return () => window.removeEventListener('message', handleMessage);
  }, [chatId,scene, modelValue, model, currentDialogInfo?.app_code, handleChat]);

  const contentRender = () => {
    if (scene === 'chat_dashboard') {
      return isContract ? <DbEditor /> : <ChatContainer />;
    } else if(scene === 'chat_excel_analyze'){
      return <ChatExcelAnalyze />
    }else{
      return isChatDefault ? (
        <Content>
          <ChatDefault />
        </Content>
      ) : (
        <Spin spinning={historyLoading} className='w-full h-full m-auto'>         
          <Content className='flex h-screen'>
            <div className='flex-1 h-full overflow-auto'>
              <ChatContentContainer ref={scrollRef} />
              <ChatInputPanel ctrl={ctrl} />
            </div>
                        
            <iframe style={{display:showAnalysis?'block':'none',width:'42%'}}
              src={ process.env.NODE_ENV === 'production' ? 
                `${window.location.origin}/login?token=${userInfo?.access_token}&url=/moreAnalysis_setting` 
                : '/moreAnalysis_setting'}               
              className="h-full border-none"
              title="更多分析"
            />                           
          </Content>
        </Spin>
      );
    }
  };

  return (
    <ChatContentContext.Provider
      value={{
        history,
        replyLoading,
        scrollRef,
        canAbort,
        chartsData: chartsData || [],
        agent,
        currentDialogue,
        appInfo,
        temperatureValue,
        maxNewTokensValue,
        resourceValue,
        modelValue,
        setModelValue,
        setResourceValue,
        setTemperatureValue,
        setMaxNewTokensValue,
        setAppInfo,
        setAgent,
        setCanAbort,
        setReplyLoading,
        handleChat,
        refreshDialogList,
        refreshHistory,
        refreshAppInfo,
        setHistory,
        showAnalysis,
        setShowAnalysis,
      }}
    >
      <Flex flex={1}>
        <Layout className='bg-gradient-light bg-cover bg-center dark:bg-gradient-dark'>
          { scene !== 'chat_excel_analyze' && <ChatSider
              refresh={refreshDialogList}
              dialogueList={dialogueList}
              listLoading={listLoading}
              historyLoading={historyLoading}
              order={order}
            />
          }
          <Layout className='bg-transparent'>{contentRender()}</Layout>
        </Layout>
      </Flex>
    </ChatContentContext.Provider>
  );
};

export default Chat;
